package com.zjitc.backend_shop.controller.Admin;


import com.zjitc.backend_shop.pojo.Admin;
import com.zjitc.backend_shop.service.AdminService;
import com.zjitc.backend_shop.utils.APIResponse;
import com.zjitc.backend_shop.utils.JwtUtils;
import com.zjitc.backend_shop.utils.Token;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RestController
@RequestMapping("/admin")
public class AdminController {
    private static final String UPLOAD_OIR = "images/";
    @Autowired
    private AdminService adminService;


    @RequestMapping("/login")
    public APIResponse<Token> login(@RequestBody Admin admin) {
        APIResponse apiResponse = new APIResponse();
        if (adminService.login(admin.getUsername(), admin.getPassword())) {
            apiResponse.setData(new Token());
            String token = JwtUtils.generateToken(admin.getUsername());
            apiResponse.APIResponseOK(0, "登录成功", new Token(token));
            return apiResponse;
        } else {
            apiResponse.APIResponseError(1000, "用户名或密码有误！", null);
            return apiResponse;
        }
    }

    @RequestMapping("/text")
    public String text() {
        return "apiResponse";
    }

    @PostMapping("/admin/changePassword")
    public APIResponse<String> changePassword(@RequestBody Admin admin, HttpServletRequest request) {
        APIResponse apiResponse = new APIResponse();

        String token = request.getHeader("jwt");
        Claims claims = JwtUtils.validateToken(token);
        admin.setUsername(claims.getSubject());

        if (adminService.changePassword(admin)) {
            apiResponse.APIResponseOK(0, "修改密码成功", null);
            return apiResponse;
        } else {
            apiResponse.APIResponseError(1000, "修改密码失败", null);
            return apiResponse;
        }
    }
    @GetMapping("/admin")
    public APIResponse<Admin> findByUsername(HttpServletRequest request){
        String token = request.getHeader("jwt");
        Claims claims = JwtUtils.validateToken(token);
        Admin admin=adminService.findByUsername(claims.getSubject());
        if(!admin.getAvatar().equals("")){
            admin.setAvatar(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/"+admin.getAvatar());
        }
        APIResponse<Admin> apiResponse = new APIResponse<>(0,"",admin);
        return apiResponse;
    }
    @PostMapping("/upload/picture")
    public APIResponse<String> uploadPicture(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        APIResponse apiResponse = new APIResponse();

        // 获取JWT Token
        String token = request.getHeader("jwt");
        Claims claims = JwtUtils.validateToken(token);

        // 处理文件上传逻辑
        if (file.isEmpty()) {
            apiResponse.APIResponseError(1001, "文件为空", null);
            return apiResponse;
        }

        try {
            Path uploadPath = Paths.get(UPLOAD_OIR);
            if(!Files.exists(uploadPath)){
                Files.createDirectories(uploadPath);
            }
            byte[] bytes = file.getBytes();
            String pathName=UUID.randomUUID()+file.getOriginalFilename();
            Path path=Paths.get(UPLOAD_OIR+pathName);
            Files.write(path,bytes);
            String pathurl=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + pathName;
            // 保存文件的逻辑
            Map<String,Object> data=new HashMap<>();
            String savepath=UPLOAD_OIR+pathName;
            data.put("savepath",savepath);
            data.put("url",pathurl);
            data.put("name",pathName);
            apiResponse.APIResponseOK(0, "图片上传成功",data);
            return apiResponse;
        } catch (Exception e) {
            apiResponse.APIResponseError(1002, "图片上传失败", null);
            return apiResponse;
        }
    }
    @PostMapping("/admin/changeAvatar")
    public APIResponse<String> changeAvator(@RequestBody Admin admin, HttpServletRequest request) {
        APIResponse apiResponse = new APIResponse();

        String token = request.getHeader("jwt");
        Claims claims = JwtUtils.validateToken(token);
        admin.setUsername(claims.getSubject());
        System.out.println(admin);
        System.out.println(1);

        if (adminService.changeAvator(admin)) {
            apiResponse.APIResponseOK(0, "修改头像成功", null);
            return apiResponse;
        } else {
            apiResponse.APIResponseError(1000, "修改头像失败", null);
            return apiResponse;
        }
    }
}
